package repository

import (
	"fmt"
	"time"
	"database/sql"
)

type App struct {
	Id       int
	AppName  string
	AppDesc  string
	AppKey   string
	DateTime time.Time
	Statas   int
	UserID   int64
	AppType  uint8
	MarkId   int
}

func (this *App) ToString() string {
	return fmt.Sprintf("%d,%s,%s,%s,%s,%d,%d,%d,%d\n", this.Id, this.AppName, this.AppDesc, this.AppKey, this.DateTime,this.Statas, this.UserID, this.AppType, this.MarkId)
}

var cache map[string] *App =make( map[string] *App,10)

func apploadall() error {

	conn, err := DbConnecton()
	if err != nil {
		return  err
	}
	defer conn.Close()
	//rows.Scan(&m.Id, &m.AppName, &m.AppDesc, &m.AppKey, &m.DateTime, &m.UserID, &m.AppType, &m.MarkId)
	cmd := "SELECT TOP 10 [AppID],[AppName],[AppDesc],[AppKey],[AddTime],[Statas],[UserID],[AppType],[MarkId] FROM [VFweMe].[dbo].[VF_App]"
	stmt, err := conn.Prepare(cmd)
	if err != nil {
		return err
	}
	rows, err := stmt.Query()
	if err != nil {
		return err
	}

	for rows.Next() {
		var entity App
		err = rows.Scan(&entity.Id, &entity.AppName, &entity.AppDesc, &entity.AppKey, &entity.DateTime,&entity.Statas, &entity.UserID, &entity.AppType, &entity.MarkId)
		if err != nil {
			return err
		}
		cache[entity.AppName]=&entity
	}
	return err
}

//func App_Find(appname string) *App  {
//
//
//	return cache[appname]
//}

func App_Find (appname string) (*App, error)  {
	var item *App =cache[appname]
	if item !=nil{

		return item,nil
	}
	conn, err := DbConnecton()
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	//rows.Scan(&m.Id, &m.AppName, &m.AppDesc, &m.AppKey, &m.DateTime, &m.UserID, &m.AppType, &m.MarkId)
	cmd := "SELECT TOP 1 [AppID],[AppName],[AppDesc],[AppKey],[AddTime],[Statas],[UserID],[AppType],[MarkId] FROM [VFweMe].[dbo].[VF_App] where AppName=@AppName"
	stmt, err := conn.Prepare(cmd)
	if err != nil {
		return nil, err
	}
	rows, err := stmt.Query(sql.Named("AppName",appname))
	if err != nil {
		return nil, err
	}
	var entity App
	if rows.Next() {

		err = rows.Scan(&(entity.Id), &entity.AppName, &entity.AppDesc, &entity.AppKey, &entity.DateTime,&entity.Statas, &entity.UserID, &entity.AppType, &entity.MarkId)
		if err != nil {
			return nil, err
		}
		cache[entity.AppName]=&entity
	}
	return &entity, err
}
